package ruralmanagementsystem.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import ruralmanagementsystem.dto.CommodityDTO;
import ruralmanagementsystem.mapper.CommodityMapper;
import ruralmanagementsystem.mapper.HouseholdMapper;
import ruralmanagementsystem.pojo.Commodity;
import ruralmanagementsystem.pojo.Household;
import ruralmanagementsystem.result.PageResult;
import ruralmanagementsystem.result.Result;
import ruralmanagementsystem.utils.JWTUtil;
import ruralmanagementsystem.vo.CommodityVO;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/commodity")
@CrossOrigin
@Slf4j
public class CommodityController {
    @Autowired
    CommodityMapper commodityMapper;

    @Autowired
    HouseholdMapper householdMapper;

    //根据id查询商品信息
    @GetMapping("/{id}")
    public Result<Commodity> getCommodityById(@PathVariable Integer id){
        return Result.success(commodityMapper.getCommodityById(id));
    }

    //分页查询全部商品
    @GetMapping
    public PageResult getAllCommodity(CommodityDTO commodityDTO){
        PageHelper.startPage(commodityDTO.getPage(), commodityDTO.getPageSize());
        Page<CommodityVO> page = commodityMapper.paginationQuery(commodityDTO);
        List<CommodityVO> records = page.getResult();
        long total = page.getTotal();
        return new PageResult(total, records);
    }

    //删除商品
    @DeleteMapping("/{id}")
    public Result deleteCommodityById(@PathVariable Integer id){
        commodityMapper.deleteCommodityById(id);
        return Result.success();
    }

    //新增商品
    @PostMapping
    public Result addCommodity(@RequestBody Commodity commodity, HttpServletRequest request){
        //设置发布者的id
        String token = request.getHeader("token");
        Claims claims = JWTUtil.parseJWT("Rural", token);
        String tele = claims.get("tele").toString();
        Household householdByHolder = householdMapper.getHouseholdByHolder(tele);
        commodity.setHousehold(householdByHolder.getId());
        //加入数据库
        commodityMapper.insertCommodity(commodity);
        return Result.success();
    }
}
